const CommonApi = require('../api/common.js');

Component({
  properties: {
    show: {type: Boolean, value: false},
    phoneNumber: {type: Number, value: null}
  },
  options:{
    addGlobalClass: true
  },
  observers: {
    show: function(){
      if (this.properties.show) {
        this.setData({
          random: Math.random(),
        })
      }
    }
  },
  data: {
    captChaImg: null,
    captchaId: null,
    random: 0,
    code: null,
    returnData: {
      valid: null,
      captchaId: null,
      captcha: null
    }
  },
  methods: {
    // 获取图形验证码
    getAppletCaptcha(){
      // 修改随机数，更新图形验证码
      this.setData({
        random: Math.random()
      })
    },
    handleInput(e){
      console.log(e.detail.value);
      this.setData({code: e.detail.value});
      if (e.detail.value.length == 4) {
        setTimeout(()=>{
          this.checkCaptcha()
        }, 200)
      }
    },
    checkCaptcha(){
      CommonApi.checkCaptcha({captchaId: this.properties.phoneNumber, code: this.data.code}).then(res=>{
        if (res.retCode == '000000' && res.errCode == '000000') {
          console.log(res);
          if (!res.data) {
            wx.showToast({icon: 'error', title: '图形验证码错误'});
          } else {
            this.setData({
              ['returnData.valid']: res.data,
              ['returnData.captchaId']: this.properties.phoneNumber,
              ['returnData.captcha']: this.data.code
            });
            this.triggerEvent('captchaData', this.data.returnData)
          }
        }
      })
    },
  }
})